package com.xigege.nio.bufferAndChannel;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author huangxi
 * @class TestByteBuffer
 * @description TestByteBuffer
 * @create 2022-08-12 12:32
 */
@Slf4j
public class BasicBufferAndChannel {
    public static void main(String[] args) throws IOException {

    }

    /**
     * 将buffer集中写入channel中
     *
     * @throws IOException
     */
    private static void gatheringWrites() throws IOException {
        // 集中写入
        ByteBuffer buffer1 = StandardCharsets.UTF_8.encode("中华民族大团结万岁");
        ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("毛主席万岁");
        ByteBuffer buffer3 = StandardCharsets.UTF_8.encode("共产党万岁");

        RandomAccessFile file = new RandomAccessFile("/Users/hx/IdeaProjects/netty_chat/words2.txt", "rw");
        FileChannel channel = file.getChannel();
        channel.write(new ByteBuffer[]{buffer1, buffer2, buffer3});
    }

    /**
     * 将channel中的数据分散读取到多个buffer中
     *
     * @throws IOException
     */
    private static void scatteringReads() throws IOException {
        //分散读取
        ByteBuffer buffer1 = ByteBuffer.allocate(3);
        ByteBuffer buffer2 = ByteBuffer.allocate(3);
        ByteBuffer buffer3 = ByteBuffer.allocate(5);

        RandomAccessFile file = new RandomAccessFile("/Users/hx/IdeaProjects/netty_chat/words.txt", "r");
        FileChannel channel = file.getChannel();

        channel.read(new ByteBuffer[]{buffer1, buffer2, buffer3});

        System.out.println(new String(buffer1.array()));
        System.out.println(new String(buffer2.array()));
        System.out.println(new String(buffer3.array()));
    }

    /**
     * 基本测试
     *
     * @throws IOException
     */
    private static void basicTest() throws IOException {
        FileChannel channel;

        FileInputStream fileInputStream = new FileInputStream("/Users/hx/IdeaProjects/netty_chat/test.txt");

        ByteBuffer buffer = ByteBuffer.allocate(1);

        channel = fileInputStream.getChannel();

        while (true) {
            int read = channel.read(buffer);
            System.out.println(read);
            if (read == -1) {
                break;
            }

            buffer.flip();
            System.out.println(new String(buffer.array()));
            buffer.clear();
//            buffer.compact();
            channel.close();
        }
    }
}
